<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Circulation Extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->page_auth->secure_page('librarian');

		$this->load->model(array(
				'M_media_types',
				'M_librarian',
				'M_student',
				'M_library_books',
				'M_enrollees',
				'M_library_book_category',
				'M_employees'
			));
		$this->load->model('M_lib_circulationfile1','m_lib_c1');
		$this->load->model('M_lib_circulationfile2','m_lib_c2');

		$this->load->helper('student_photo');
		$this->load->helper('library');
		$this->load->helper('panel');
		$this->_init_pagnate_config();
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['use_bootstrap3'] = true; // TO INCLUDE BOOTSTRAP JS IN TEMPLATE, reason putting it as it is brokes the foundation js, include only when use
	}

	public function profile($usertype=false, $id = false)
	{
		if(!$usertype){ show_404(); }
		if(!$id){ show_404(); }

		$this->view_data['usertype'] = $usertype;
		$this->view_data['id'] = $id;
		if($usertype === "student"){
 			$this->view_data['student'] = $user = $this->M_student->get_student($id);
 		}else{
 			$this->view_data['employee'] = $user = $this->M_employees->get($id);
 			$this->view_data['fullname'] = $user ? $user->last_name.', '.$user->first_name.' '.$user->middle_name  : '';
 		}

 		if(!$user){ show_404(); }

 		$this->view_data['transactions'] = $this->m_lib_c1->get_active_transactions($usertype, $id);

 		/******** CATCH THE RETURN SUBMIT BUTTON ********/
 		if($this->input->post('return_selected')){

 			if($this->input->post('chk_return')){
 				$rs = $this->m_lib_c2->return_details($this->input->post('chk_return'));
 				if($rs){

 					$this->_msg('s','Record was successfully return.', current_url());
 				}else{
 					$this->_msg('e','Transaction failed, please try again', current_url());
 				}
 			}else{
 				$this->_msg('e','No selected item to be return.', current_url());
 			}
 		}

 		/******** CATCH THE DELETE ITEM BUTTON ********/
 		if($this->input->post('remove_selected')){

 			if($this->input->post('chk_return')){
 				$rs = $this->m_lib_c2->remove_details($this->input->post('chk_return'));
 				if($rs){

 					$this->_msg('s','Record was successfully deleted.', current_url());
 				}else{
 					$this->_msg('e','Transaction failed, please try again', current_url());
 				}
 			}else{
 				$this->_msg('e','No selected item to be deleted.', current_url());
 			}
 		}
	}

	public function history($usertype = false, $id = false, $page = 0)
	{
		if(!$usertype){ show_404(); }
		if(!$id){ show_404(); }

		$this->view_data['usertype'] = $usertype;
		$this->view_data['id'] = $id;
		if($usertype === "student"){
 			$this->view_data['student'] = $user = $this->M_student->get_student($id);
 		}else{
 			$this->view_data['employee'] = $user = $this->M_employees->get($id);
 			$this->view_data['fullname'] = $user ? $user->last_name.', '.$user->first_name.' '.$user->middle_name  : '';
 		}

 		if(!$user){ show_404(); }

 		/*** For PAGINATION ***/

		$like = false;
		$order_by = false;
		$filter['lib_circulationfile2.is_deleted'] = 0;
		$filter['lib_circulationfile1.usertype'] = $usertype;
		$filter['lib_circulationfile1.borrower_id'] = $id;
		$filter['lib_circulationfile1.is_deleted'] = 0;
		$filter['lib_circulationfile1.status'] = 'RETURN';
		
		/* GET SEARCH KEYWORDS AND ADD TO FILTER */
		if($_GET)
		{	
			if(isset($_GET['item_name']) && $_GET['item_name'] != ""){
				$this->view_data['item_name'] = $like['library_books.book_name'] = trim($_GET['item_name']); }
		}
		
		//CONFIGURATION
		$get['fields'] = array(
				'library_books.book_name',
				'library_books.book_desc',
				'library_books.book_barcode',
				'library_books.accession_number',
				'library_books.call_number',
				'lib_circulationfile1.trndte',
				'lib_circulationfile1.remarks',
				'lib_circulationfile2.retdte',
				'lib_circulationfile2.cir_status',
				'lib_circulationfile2.day',
				'lib_circulationfile2.is_late',
		);
		
		$get['where'] = $filter;
		$get['like'] = $like;

		$get['join'][] = array(
				'table' => 'lib_circulationfile1',
				'on' => 'lib_circulationfile1.id = lib_circulationfile2.circulation_id',
				'type' => 'left'
			);

		$get['join'][] = array(
				'table' => 'library_books',
				'on' => 'library_books.book_id = lib_circulationfile2.media_id',
				'type' => 'left'
			);
		
		$get['order'] = "lib_circulationfile1.trndte DESC,lib_circulationfile2.id DESC";
		$get['all'] = true; //GET ALL EXCLUDE LIMIT
		$get['count'] = true; //RETURN COUNT NOT ROW
		$get['array'] = false; //RETURN OBJECT NOT ARRAY
		$get['single'] = false; //RETURN ALL NOT SINGLE
		
	
		$this->load->library("pagination");
		$config = $this->pagnate_config;
		$config["base_url"] = base_url() ."circulation/history/".$usertype.'/'.$id;
		$suffix = '?'.http_build_query($_GET, '', "&");
		$suffix = str_replace("&submit=Search", "", $suffix);
		$config['suffix'] = $suffix;
		$this->view_data['current_url'] = $config['first_url'] = $config['base_url'].$config['suffix']; 
		
		$this->view_data['total_rows'] = $config["total_rows"] = $this->m_lib_c2->get_record(false, $get);
		
		$config["per_page"] = 25;
		$config['num_links'] = 10;
		$config["uri_segment"] = 5;
		// $config['use_page_numbers'] = TRUE;
		$this->pagination->initialize($config);
		
		//FOR PAGINATION
		$get['all'] = false;
		$get['count'] = false;
		$get['start'] = $page;
		$get['limit'] = $config['per_page'];
		
		$this->view_data['search'] = $search = $this->m_lib_c2->get_record(false, $get);
		$this->view_data['links'] = $this->pagination->create_links();

		/*** End of PAGINATION ***/
	}

	public function borrowed_media($page = 0)
	{
		$this->view_data['media_types'] = $this->M_media_types->get_for_dd(array('id','media_type'), false, 'All Types','media_type');
		$this->view_data['book_category'] = $this->M_library_book_category->get_for_dd(array('lbc_id','lbc_name'), false, 'All Categories','lbc_name');

 		/*** For PAGINATION ***/

		$like = false;
		$order_by = false;
		$filter['library_books.book_borrowed > '] = 0;
		
		/* GET SEARCH KEYWORDS AND ADD TO FILTER */
			if($_GET)
			{	
				if(isset($_GET['item_name']) && $_GET['item_name'] != ""){
					$this->view_data['item_name'] = $like['library_books.book_name'] = trim($_GET['item_name']); }

				if(isset($_GET['accession_number']) && $_GET['accession_number'] != ""){
					$this->view_data['accession_number'] = $like['library_books.accession_number'] = trim($_GET['accession_number']); }
			
				if(isset($_GET['call_number']) && $_GET['call_number'] != ""){
					$this->view_data['call_number'] = $like['library_books.call_number'] = trim($_GET['call_number']); }

				if(isset($_GET['item_barcode']) && $_GET['item_barcode'] != ""){
					$this->view_data['item_barcode'] = $like['library_books.book_barcode'] = trim($_GET['item_barcode']); }

				if(isset($_GET['item_author']) && $_GET['item_author'] != ""){
					$this->view_data['item_author'] = $like['library_books.book_author'] = trim($_GET['item_author']); }

				if(isset($_GET['item_isbn']) && $_GET['item_isbn'] != ""){
					$this->view_data['item_isbn'] = $like['library_books.book_isbn'] = trim($_GET['item_isbn']); }

				if(isset($_GET['item_type']) && $_GET['item_type'] != ""){
					$this->view_data['item_type'] = $filter['library_books.media_type_id'] = trim($_GET['item_type']); }

				if(isset($_GET['item_category']) && $_GET['item_category'] != ""){
					$this->view_data['item_category'] = $filter['library_books.book_category'] = trim($_GET['item_category']); }
			}
		
		/* CONFIGURATION */
			$get['fields'] = array(
					'library_books.*',
					'library_book_category.lbc_name as category',
					'book_copies - book_borrowed as available',
					'media_types.media_type',
			);
			
			$get['where'] = $filter;
			$get['like'] = $like;
			
			$get['join'][] = array(
					'table' => 'media_types',
					'on' => 'library_books.media_type_id = media_types.id',
					'type' => 'left'
				);

			$get['join'][] = array(
					'table' => 'library_book_category',
					'on' => 'library_books.book_category = library_book_category.lbc_id',
					'type' => 'left'
				);
			
			$get['order'] = "library_books.book_name";
			$get['all'] = true; //GET ALL EXCLUDE LIMIT
			$get['count'] = true; //RETURN COUNT NOT ROW
			$get['array'] = false; //RETURN OBJECT NOT ARRAY
			$get['single'] = false; //RETURN ALL NOT SINGLE
		
		$this->load->library("pagination");
		$config = $this->pagnate_config;
		$config["base_url"] = base_url() ."circulation/borrowed_media";
		$suffix = '?'.http_build_query($_GET, '', "&");
		$suffix = str_replace("&submit=Search", "", $suffix);
		$config['suffix'] = $suffix;
		$this->view_data['current_url'] = $config['first_url'] = $config['base_url'].$config['suffix']; 
		
		$this->view_data['total_rows'] = $config["total_rows"] = $this->M_library_books->get_record(false, $get);
		
		$config["per_page"] = 25;
		$config['num_links'] = 10;
		$config["uri_segment"] = 3;
		// $config['use_page_numbers'] = TRUE;
		$this->pagination->initialize($config);
		
		//FOR PAGINATION
		$get['all'] = false;
		$get['count'] = false;
		$get['start'] = $page;
		$get['limit'] = $config['per_page'];
		
		$this->view_data['search'] = $search = $this->M_library_books->get_record(false, $get);
		$this->view_data['links'] = $this->pagination->create_links();

		/*** End of PAGINATION ***/

		/** get borrowers **/
		$borrowers = false;
		if($search){
			foreach ($search as $key => $i) {
				$borrowers[$i->book_id] = $this->m_lib_c2->get_borrowers($i->book_id);
			}
		}
		$this->view_data['borrowers'] = $borrowers;
	}

	public function index($page = 0)
	{
		$this->view_data['media_types'] = $this->M_media_types->get_for_dd(array('id','media_type'), false, 'All Types','media_type');
		$this->view_data['book_category'] = $this->M_library_book_category->get_for_dd(array('lbc_id','lbc_name'), false, 'All Subjects','lbc_name');

		/*** For PAGINATION ***/

		$filter = false;
		$like = false;
		$order_by = false;
		
		$arr_filters = array();
		$suffix = "";
		
		/* GET SEARCH KEYWORDS AND ADD TO FILTER */
		if($_GET)
		{	
			if(isset($_GET['item_name']) && $_GET['item_name'] != ""){
				$this->view_data['item_name'] = $like['library_books.book_name'] = trim($_GET['item_name']); }

			if(isset($_GET['accession_number']) && $_GET['accession_number'] != ""){
				$this->view_data['accession_number'] = $like['library_books.accession_number'] = trim($_GET['accession_number']); }
			
			if(isset($_GET['call_number']) && $_GET['call_number'] != ""){
				$this->view_data['call_number'] = $like['library_books.call_number'] = trim($_GET['call_number']); }

			if(isset($_GET['item_barcode']) && $_GET['item_barcode'] != ""){
					$this->view_data['item_barcode'] = $like['library_books.book_barcode'] = trim($_GET['item_barcode']); }

			if(isset($_GET['item_author']) && $_GET['item_author'] != ""){
				$this->view_data['item_author'] = $like['library_books.book_author'] = trim($_GET['item_author']); }

			if(isset($_GET['item_isbn']) && $_GET['item_isbn'] != ""){
				$this->view_data['item_isbn'] = $like['library_books.book_isbn'] = trim($_GET['item_isbn']); }

			if(isset($_GET['item_type']) && $_GET['item_type'] != ""){
				$this->view_data['item_type'] = $filter['library_books.media_type_id'] = trim($_GET['item_type']); }

			if(isset($_GET['item_category']) && $_GET['item_category'] != ""){
				$this->view_data['item_category'] = $filter['library_books.book_category'] = trim($_GET['item_category']); }
		}
		
		//CONFIGURATION
		$get['fields'] = array(
				'library_books.*',
				'library_book_category.lbc_name as category',
				'book_copies - book_borrowed as available',
				'media_types.media_type',
		);
		
		$get['where'] = $filter;
		$get['like'] = $like;

		$get['join'][] = array(
				'table' => 'media_types',
				'on' => 'library_books.media_type_id = media_types.id',
				'type' => 'left'
			);

		$get['join'][] = array(
				'table' => 'library_book_category',
				'on' => 'library_books.book_category = library_book_category.lbc_id',
				'type' => 'left'
			);
		
		$get['order'] = "library_books.book_name";
		$get['all'] = true; //GET ALL EXCLUDE LIMIT
		$get['count'] = true; //RETURN COUNT NOT ROW
		$get['array'] = false; //RETURN OBJECT NOT ARRAY
		$get['single'] = false; //RETURN ALL NOT SINGLE
		
	
		$this->load->library("pagination");
		$config = $this->pagnate_config;
		$config["base_url"] = base_url() ."circulation/index";
		$suffix = '?'.http_build_query($_GET, '', "&");
		$suffix = str_replace("&submit=Search", "", $suffix);
		$config['suffix'] = $suffix;
		$this->view_data['current_url'] = $config['first_url'] = $config['base_url'].$config['suffix']; 
		
		$this->view_data['total_rows'] = $config["total_rows"] = $this->M_library_books->get_record(false, $get);
		
		$config["per_page"] = 25;
		$config['num_links'] = 10;
		$config["uri_segment"] = 5;
		// $config['use_page_numbers'] = TRUE;
		$this->pagination->initialize($config);
		
		//FOR PAGINATION
		$get['all'] = false;
		$get['count'] = false;
		$get['start'] = $page;
		$get['limit'] = $config['per_page'];
		
		$this->view_data['search'] = $search = $this->M_library_books->get_record(false, $get);
		$this->view_data['links'] = $this->pagination->create_links();

		/*** End of PAGINATION ***/
	}

	public function borrow($usertype = false, $id = false, $page = 0)
	{
		if($id === false){ show_404(); }
		if($usertype === false){ show_404(); }

		/* VALIDATE PARAMETERS */
		if($usertype === "student"){
			$this->view_data['student'] = $user = $this->M_student->get_student($id);
			if(!$user){ show_404(); }
		}else if($usertype === "employee"){
			$this->view_data['employee'] = $user = $this->M_employees->get($id);
 			$this->view_data['fullname'] = $user ? $user->last_name.', '.$user->first_name.' '.$user->middle_name  : '';
			if(!$user){ show_404(); }
		}else{ show_404(); }

		$this->view_data['id'] = $id;
		$this->view_data['usertype'] = $usertype;
		$this->view_data['library_cart'] = $this->_get_library_cart($id); // get save item in the session to be shoot inside the cart
		// vp($this->session->userdata);
		//Load dropdowns
		$this->view_data['media_types'] = $this->M_media_types->get_for_dd(array('id','media_type'), false, 'All Types','media_type');
		$this->view_data['book_category'] = $this->M_library_book_category->get_for_dd(array('lbc_id','lbc_name'), false, 'All Subjects','lbc_name');

		/*** For PAGINATION ***/

		$filter = false;
		$like = false;
		$order_by = false;
		
		$arr_filters = array();
		$suffix = "";
		
		/* GET SEARCH KEYWORDS AND ADD TO FILTER */
		if($_GET)
		{	
			if(isset($_GET['item_name']) && $_GET['item_name'] != ""){
				$this->view_data['item_name'] = $like['library_books.book_name'] = trim($_GET['item_name']); }

			if(isset($_GET['accession_number']) && $_GET['accession_number'] != ""){
				$this->view_data['accession_number'] = $like['library_books.accession_number'] = trim($_GET['accession_number']); }
			
			if(isset($_GET['call_number']) && $_GET['call_number'] != ""){
				$this->view_data['call_number'] = $like['library_books.call_number'] = trim($_GET['call_number']); }	

			if(isset($_GET['item_barcode']) && $_GET['item_barcode'] != ""){
					$this->view_data['item_barcode'] = $like['library_books.book_barcode'] = trim($_GET['item_barcode']); }

			if(isset($_GET['item_author']) && $_GET['item_author'] != ""){
				$this->view_data['item_author'] = $like['library_books.book_author'] = trim($_GET['item_author']); }

			if(isset($_GET['item_isbn']) && $_GET['item_isbn'] != ""){
				$this->view_data['item_isbn'] = $like['library_books.book_isbn'] = trim($_GET['item_isbn']); }

			if(isset($_GET['item_type']) && $_GET['item_type'] != ""){
				$this->view_data['item_type'] = $filter['library_books.media_type_id'] = trim($_GET['item_type']); }

			if(isset($_GET['item_category']) && $_GET['item_category'] != ""){
				$this->view_data['item_category'] = $filter['library_books.book_category'] = trim($_GET['item_category']); }

			// CATCH BORROWING ITEM
			if(isset($_GET['add_to_cart']) && $_GET['add_to_cart'] != ""){

				$addc = $this->_add_to_cart($usertype, $id, $_GET['add_to_cart']);
				if($addc->status){
					$this->_msg('s',$addc->msg, current_url());
				}else{
					$this->_msg('e',$addc->msg, current_url());
				}
			}
		}
		
		//CONFIGURATION
		$get['fields'] = array(
				'library_books.*',
				'library_book_category.lbc_name as category',
				'book_copies - book_borrowed as available',
				'media_types.media_type',
		);

		$filter['(book_copies - book_borrowed) > '] = 0;
		
		$get['where'] = $filter;
		$get['like'] = $like;
		$get['not_in'] = array(
				'field' => 'library_books.book_id',
				'data' => $this->_get_library_cart($id, true)
			);

		$get['join'][] = array(
				'table' => 'media_types',
				'on' => 'library_books.media_type_id = media_types.id',
				'type' => 'left'
			);

		$get['join'][] = array(
				'table' => 'library_book_category',
				'on' => 'library_books.book_category = library_book_category.lbc_id',
				'type' => 'left'
			);
		
		$get['order'] = "library_books.book_name";
		$get['all'] = true; //GET ALL EXCLUDE LIMIT
		$get['count'] = true; //RETURN COUNT NOT ROW
		$get['array'] = false; //RETURN OBJECT NOT ARRAY
		$get['single'] = false; //RETURN ALL NOT SINGLE
		
	
		$this->load->library("pagination");
		$config = $this->pagnate_config;
		$config["base_url"] = base_url() ."circulation/borrow/".$usertype.'/'.$id;
		$suffix = '?'.http_build_query($_GET, '', "&");
		$suffix = str_replace("&submit=Search", "", $suffix);
		$config['suffix'] = $suffix;
		$this->view_data['current_url'] = $config['first_url'] = $config['base_url'].$config['suffix']; 
		
		$this->view_data['total_rows'] = $config["total_rows"] = $this->M_library_books->get_record(false, $get);
		
		$config["per_page"] = 25;
		$config['num_links'] = 10;
		$config["uri_segment"] = 5;
		// $config['use_page_numbers'] = TRUE;
		$this->pagination->initialize($config);
		
		//FOR PAGINATION
		$get['all'] = false;
		$get['count'] = false;
		$get['start'] = $page;
		$get['limit'] = $config['per_page'];
		
		$this->view_data['search'] = $search = $this->M_library_books->get_record(false, $get);
		$this->view_data['links'] = $this->pagination->create_links();

		/*** End of PAGINATION ***/


		$this->view_data['system_message'] = $this->_msg();
		$this->load->library('token');
		$this->token->set_token();
		$this->view_data['token'] = $this->token->get_token();

		// CAPTURE BORROWING AND RESERVING PROCESS
		if($this->input->post('checkout') && $this->input->post('cart')){

			if($this->token->validate_token($this->input->post('form_token')))
			{
				$this->form_validation->set_rules('trndte','Transaction Date','required|trim|date|htmlspecialchars');
				if($this->form_validation->run() !== FALSE)
				{
					$rs = $this->m_lib_c1->check_out();

					/** Check if saved errors **/
					if($rs->status){

						if($rs->unavailable){ // if some book was already unavaliable

							$msg = " Some Item/s was already unavaliable";

							$this->_msg('s',$rs->msg.$msg, current_url());
						}else{

							unset($this->session->userdata['library_cart'][$id]);

							$this->_msg('s',$rs->msg, 'circulation/profile/'.$usertype.'/'.$id);
						}
					}else{
						$this->_msg('e',$rs->msg, current_url());
					}

				}else{
					$this->view_data['system_message'] = '<div class="alert alert-danger">'.validation_errors().'</div>';
				}
			}
			else
			{
				$this->_msg('e','Submit failed form token Expired, Please try again ',current_url());
			}
		}
	}

	/**
	 * Add to cart
	 * Save item in the session
	 */
	private function _add_to_cart($usertype = false, $id = false, $book_id = false)
	{
		if($usertype===false){ show_404(); }
		if($id===false){ show_404(); }
		if($book_id===false){ show_404(); }

		$sly = new stdClass;
		$sly->status = false;
		$sly->msg = "";

		// check if book exist and available
		$item = $this->M_library_books->get($book_id);
		if(!$item){ show_404(); }

		if(($item->book_copies - $item->book_borrowed) <= 0){
			$sly->msg = "Item was already unavailable";
			return $sly;
		}
		
		if($this->session->userdata('library_cart') === false){
			unset($books);
			$books[$id][] = $book_id;
			$this->session->set_userdata('library_cart', $books);
		}else{
			
			$data = $this->session->userdata('library_cart');

			if(!isset($data[$id])){
				unset($books);
				$data[$id][] = $book_id;
				$this->session->set_userdata('library_cart', $data);
			}else
			{
				$added_books = $data[$id];
				
				// check if book_id already in array
				if(is_array($added_books) && in_array($book_id, $added_books)){
					$sly->msg = "Item Already in the Cart";
					return $sly;
				}

				$data[$id][] = $book_id;
				$this->session->set_userdata('library_cart', $data);
			}
		}
		// vd($this->session->set_userdata('library_cart'));
		$sly->status = true;
		$sly->msg = "Item was successfully added to cart";
		return $sly;
	}

	/**
	 * Remove Item in cart
	 * Remove the book in the session
	 */
	public function remove_item_in_cart($usertype = false, $id = false, $book_id = false)
	{
		if($usertype===false){ show_404(); }
		if($id===false){ show_404(); }
		if($book_id===false){ show_404(); }

		$cart = $this->session->userdata['library_cart'][$id];
		
		if(isset($this->session->userdata['library_cart'][$id])){
			$key = array_search($book_id, $cart); 
			unset($this->session->userdata['library_cart'][$id][$key]);
			$this->_msg('s','Item was successfully removed from the cart','circulation/borrow/'.$usertype.'/'.$id);
		}
		
		$this->_msg('e','Item failed to be removed.','circulation/borrow/'.$usertype.'/'.$id);
	}

	/**
	 * Delete Transaction
	 * Remove borrowed transaction - only update is_deleted to 1
	 */
	public function delete_transaction($usertype = false, $id = false, $lib_id = false)
	{
		if($usertype===false){ show_404(); }
		if($id===false){ show_404(); }
		if($lib_id===false){ show_404(); }

		$item  = $this->m_lib_c1->pull($lib_id, 'id');
		if(!$item){ show_404(); }
		if(has_return_item($lib_id)){ // if transaction already has a return
			$this->_msg('e','Transaction cannot be deleted.','circulation/profile/'.$usertype.'/'.$id);
		}

		if($this->m_lib_c1->delete_transaction($lib_id)){
			$this->_msg('s','Transaction was removed successfully.','circulation/profile/'.$usertype.'/'.$id);	
		}
		
		$this->_msg('e','Transaction failed please try again.','circulation/profile/'.$usertype.'/'.$id);
	}

	/**
	 * Get Library Cart
	 * @return array of item/media/books
	 */
	private function _get_library_cart($id, $return_ids = false)
	{
		$cart = $this->session->userdata('library_cart');

		if(isset($cart[$id]) && $cart[$id]){
			
			$cart = $cart[$id];
			// vp($cart);
			$items = false;
			foreach ($cart as $key => $_id) {
				// vp($_id);
				$get = $this->M_library_books->get(array('book_id'=>$_id));
				if($get){
					$items[] = $get;
				}
			}
			
			if($return_ids){
				return $cart;
			}

			return $items;

		}		

		return false;
	}

	/**
	 * Upload Media CSV
	 * Upload Data From CSV File
	 */
	public function upload_media_csv()
	{
		$this->load->library('token');
		$this->token->set_token();
		$this->view_data['token'] = $this->token->get_token();		

		if($this->input->post('upload_csv') && $_FILES['userfile']['name'] ){
			
			if($this->token->validate_token($this->input->post('form_token'))){

				set_time_limit(0);
				$config['upload_path'] = './assets/uploads/school';
				$config['allowed_types'] = 'csv';
				$config['max_size']	= '10000';
				$config['file_name'] = 'library_media_upload';
				$config['overwrite'] = TRUE;
				$config['width']	 = 188;
				$config['height'] = 187;
				$this->load->library('upload', $config);
				
				if ( ! $this->upload->do_upload()){

					$this->view_data['system_message'] = $this->_msg('e',' '.$this->upload->display_errors());
				}else{
					
					$data = array('upload_data' => $this->upload->data());
					//resize start
					$source_path = $data['upload_data']['full_path'];

					$up = $this->M_library_books->upload_from_csv($source_path);

					if($up->status){

						$this->_msg('s', $up->msg, current_url());
					}else{
						$this->_msg('e',$up->msg,current_url());
					}	
				}

			}else{
				$this->_msg('e','Upload Form breached!', current_url());
			}
		}
	}

	/**
	 * Download Media CSV format
	 */
	public function download_media_csv_format()
	{
		$this->load->helper('csv');
    	
		array_to_csv($this->_media_csv_format(), 'media_format_v1.csv');
	}

	private function _media_csv_format($return_fields = false){
		$fields = array();
		$fields[0][0] = 'Media Type';
		$fields[0][1] = 'Media Subject';
		$fields[0][2] = 'Media Accession Number';
		$fields[0][3] = 'Media Call Number';
		$fields[0][4] = 'Media Title';
		$fields[0][5] = 'Media Description';
		$fields[0][6] = 'Number of Copies (Integer)';	
		$fields[0][7] = 'Media ISBN';
		$fields[0][8] = 'Media Author';	
		$fields[0][9] = 'Media Publisher';	
		$fields[0][10] = 'Date Publish (yyyy-mm-dd)';
		$fields[0][11] = 'Barcode';

		if($return_fields){
			$fields = array( 
				'Subject',
				'Type',
	    		'Acc. No.',
				'Call No.',
				'Title',
	    		'Description',
	    		'Barcode',
	    		'Author',
	    		'ISBN',
	    		'Publisher',
	    		'Date Pub.',
	    		'Qty');
		}

		return $fields;
	}

	/***  REPORTS  ***/

	public function media_master_list($id = false)
	{
		$this->view_data['type'] = $t = $this->M_library_books->get_master_list_by_type();
		$this->view_data['category'] = $this->M_library_books->get_master_list_by_category();
	}

	public function download_media_category_master($id = false)
	{
		$this->load->helper('csv');

		$cat = $this->M_library_books->get_master_list_by_category($id);

		$format = $this->_media_csv_format(true);

		$sly[] = array();
		$sly[] = $format;
		
		if($cat){
			foreach ($cat as $key => $c) {
				$h = $c['head'];
				$t = $c['tail'];
				
				if(!$t){ continue; }

				foreach ($t as $k => $b) {

					$ct = $k == 0 ? $h->lbc_name : '';

					$sly[] = array(
						$ct,
						$b->media_type,
						$b->accession_number,
						$b->call_number,
						$b->book_name,
						$b->book_desc,
						$b->book_barcode,
						$b->book_author,
						$b->book_isbn,
						$b->book_publisher,
						$b->book_dop && $b->book_dop !== "1970-01-01" ? date('m/d/Y', strtotime($b->book_dop)) : '',
						$b->book_copies,
					);
				}

			}
		}

		array_to_csv($sly, 'category_master_list.csv');
	}

	public function download_media_type_master($id = false)
	{
		$this->load->helper('csv');

		$cat = $this->M_library_books->get_master_list_by_type($id);

		$format = $this->_media_csv_format(true);

		$sly[] = array();
		$sly[] = $format;
		
		if($cat){
			foreach ($cat as $key => $c) {
				$h = $c['head'];
				$t = $c['tail'];
				
				if(!$t){ continue; }

				foreach ($t as $k => $b) {

					$ct = $k == 0 ? $h->media_type : '';

					$sly[] = array(
						$ct,
						$b->media_type,
						$b->accession_number,
						$b->call_number,
						$b->book_name,
						$b->book_desc,
						$b->book_barcode,
						$b->book_author,
						$b->book_isbn,
						$b->book_publisher,
						$b->book_dop && $b->book_dop !== "1970-01-01" ? date('m/d/Y', strtotime($b->book_dop)) : '',
						$b->book_copies,
					);
				}

			}
		}

		array_to_csv($sly, 'media_type_master_list.csv');
	}

	public function download_all_media_master()
	{
		$this->load->helper('csv');

		set_time_limit(0);

		unset($get);
		$data['school_name'] = $this->school_name;
		$get['order'] = 'book_name';
		$get['fields'] = array(
				'library_books.*',
				'library_book_category.lbc_name as category',
				'book_copies - book_borrowed as available',
				'media_types.media_type',
		);

		$get['join'][] = array(
				'table' => 'media_types',
				'on' => 'library_books.media_type_id = media_types.id',
				'type' => 'left'
			);

		$get['join'][] = array(
				'table' => 'library_book_category',
				'on' => 'library_books.book_category = library_book_category.lbc_id',
				'type' => 'left'
			);
		
		$search = $this->M_library_books->get_record(false, $get);

		$sly[] = $this->_media_csv_format(true);
		if($search){
			foreach ($search as $key => $b) {
				
				$sly[] = array(
						$b->media_type,
						$b->category,
						$b->accession_number,
						$b->call_number,
						$b->book_name,
						$b->book_desc,
						$b->book_barcode,
						$b->book_author,
						$b->book_isbn,
						$b->book_publisher,
						$b->book_dop && $b->book_dop !== "1970-01-01" ? date('m/d/Y', strtotime($b->book_dop)) : '',
						$b->book_copies,
					);
			}
		}

		array_to_csv($sly, 'media_master_list.csv');
	}

	public function circulation_report()
	{
		//Load dropdowns
		$this->view_data['media_types'] = $this->M_media_types->get_for_dd(array('id','media_type'), false, 'All Types','media_type');
		$this->view_data['book_category'] = $this->M_library_book_category->get_for_dd(array('lbc_id','lbc_name'), false, 'All Subjects','lbc_name');
		$this->view_data['students'] = $this->M_enrollees->get_student_for_dd();
		$this->view_data['employees'] = $this->M_employees->get_employees_for_dd();
		$this->view_data['medias'] = $this->M_library_books->get_for_dd(array('book_name','book_name'),false, "Select Media",'book_name');

	}

	/***  END OF REPORTS  ***/
}